package server;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * <h1>Class Conversation.</h1>
 * 
 * A conversation represents a flow of messages between 2 or more users in the system.
 * It has a collection of sessions which are the ones who need to receive the messages 
 * sent in that conversation.
 * 
 * @author Tomas
 * @date March 4 2009
 */
public class Conversation {

	/**
	 * People involved in the conversation.
	 * To be implemented as an ArrayList.
	 */
	protected List<Session> participants = null;
	
	/**
	 * Conversation ID. It is created with the concatenation of the username of
	 * the creator of the conversation and a number (obtained from the number of
	 * conversations created since the start of the system). This is to enforce 
	 * different IDs for the conversations.  
	 */
	protected String convID = null;
	
	/**
	 * Number of conversations since the starting of the system. It is used to
	 * generate IDs for the conversation. We use long to prevent numbers cycling.
	 */
	protected static long numConversations = 0;
	
	/**
	 * Initializes an instance of the class Conversation. To create a Conversation,
	 * we need at least one Session (we don't need two since we can deliver messages
	 * to people who are offline, and in that case we'll just store the messages in
	 * the database. 
	 * 
	 * @param s1
	 * 		Creator of the conversation.
	 */
	public Conversation(Session s1){
		
		participants = new ArrayList<Session>();
		participants.add(s1);
		
		convID = s1.getOwner().getUsername() + numConversations;
		numConversations++;
		
	}
	
	/**
	 * Adds a new participant to the conversation.
	 * 
	 * @param s
	 * 		Participant to be added.
	 */
	public void addParticipant(Session s){
		
		participants.add(s);
		
		// TODO: notify the participants about the new one.
		
	}
	
	/**
	 * Obtains all the participants in the conversation.
	 * 
	 * @return
	 * 		Iterator over the participants in the conversation.
	 */
	public Iterator<Session> getParticipants(){
		
		return participants.iterator();
		
	}
	
	/**
	 * Removes a participant from the conversation.
	 * 
	 * @param s
	 * 		Participant to be removed from the conversation.
	 * @return
	 * 		Boolean value telling if the operation was successful or not.
	 */
	public boolean removeParticipant(Session s){
		
		if(participants.contains(s)){
			participants.remove(s);
			return true;
		}else{
			return false;
		}
	}
	
	/**
	 * Obtains the ID for the conversation.
	 * 
	 * @return
	 * 		String object with the conversation ID
	 */
	public String getID(){
		
		return convID;
		
	}
}
